package com.ywy.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.ywy.util.SignUtil;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class ApiClient {
    private static final String GATEWAY_HOST = "http://localhost:8102";

    private String accessKey;
    private String secretKey;

    public ApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    /**
     * 请求接口
     * @param url
     * @param params
     * @return
     */
    public String send(String url, String params) {
        HttpResponse response = HttpRequest.post(GATEWAY_HOST + url)
                .charset(StandardCharsets.UTF_8)
                .addHeaders(getHeaderMap(params))
                .body(params)
                .execute();
        return response.body();
    }

    /**
     * 获取请求头
     * @param body
     * @return
     */
    private Map<String, String> getHeaderMap(String body) {
        Map<String, String> hashMap = new HashMap<>();
        hashMap.put("accessKey", accessKey);
        hashMap.put("nonce", RandomUtil.randomNumbers(4));
//        hashMap.put("body", body);
        hashMap.put("timestamp", String.valueOf(System.currentTimeMillis()/1000));
        hashMap.put("sign", SignUtil.genSign(body, secretKey));

        return hashMap;
    }
}
